package mspbots.cw.callbacks.core.notice;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.callbacks.core.CallbackMessage;
import mspbots.cw.common.annotation.ApiException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

/**
 * com.mspbots.sync.callback.NoticeController
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/7/12
 */
@Log4j2
@RequiredArgsConstructor
@RestController
@RequestMapping("notice/{tenant}")
public class NoticeController {

    private final NoticeService noticeService;

    @PostMapping("callback")
    public Mono<String> noticeCallback(@PathVariable Long tenant,
                                       @RequestBody Mono<CallbackMessage> callbackMessageMono,
                                       @RequestHeader("X-Content-Signature") String signature) {
        return callbackMessageMono
                .doOnNext(callbackMessage ->
                        log.debug("Notice [{}] call back entry id:{},type:{},action:{}",
                                tenant, callbackMessage.getId(), callbackMessage.getType(), callbackMessage.getAction()))
                .filter(callbackMessage -> callbackMessage.getId() > 0)
                .switchIfEmpty(Mono.error(new ApiException(HttpStatus.NOT_FOUND, "Call back request data exception.")))
                .map(callbackMessage -> callbackMessage.setTenantId(tenant))
                .map(this.noticeService::sender)
                .filter(result -> result > 0)
                .map(v -> "SUCCESS")
                .defaultIfEmpty("error");
    }

}
